package com.leetcode.LC_MED;

import java.util.Stack;

public class LC394 {
    //https://leetcode-cn.com/problems/decode-string/solution/decode-string-fu-zhu-zhan-fa-di-gui-fa-by-jyd/
    public String decodeString(String s) {

        StringBuilder res = new StringBuilder();
        int multi = 0;

        Stack<Integer> stack_multi = new Stack<>();
        Stack<String> stack_res = new Stack<>();

        for (char c : s.toCharArray()) {
            if (c <= '9' && c >= '0') {
                multi = multi * 10 + c - '0';//注意数字可能是多位数
            } else if (c == '[') {
                stack_multi.push(multi);
                stack_res.push(res.toString());
                res = new StringBuilder();
                multi = 0;
            } else if (c <= 'z' && c >= 'a') {
                res.append(c);
            } else if (c == ']') {
                int k = stack_multi.pop();
                String str = stack_res.pop();
                String tmp = res.toString();
                res = new StringBuilder();
                res.append(str);
                for (int i = 0; i < k; i++) {
                    res.append(tmp);
                }
            }
        }
        return res.toString();
    }

    public static void main(String[] args) {
        System.out.println(new LC394().decodeString("3[a2[c]]"));
    }
}
